<!DOCTYPE html>
<html lang='en'>
  <head>
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <title>Sample Page</title>
    <link rel="stylesheet" href="/static/css/bootstrap.css">
    <style type="text/css" media="screen">
    canvas, img { display:block; margin:0; border:0; }
    canvas { background:url(/static/img/map.jpg) }

    #wrapper {
        position: relative;
        border: 1px solid #9C9898;
        width: 500px;
        height: 500px;
    }

    #buttonWrapper {
                position: absolute;
                width: 30px;
                top: 2px;
                right: 2px;
    }

    input[type = "button"] {
                padding: 5px;
                width: 30px;
                margin: 0px 0px 2px 0px;
    }
      body {
        padding-top: 60px;
        padding-bottom: 40px;
      }


    </style>
    <script type="text/javascript" src="/static/js/websocket.js"></script>
    <script type="text/javascript" src="/static/js/jquery.js"></script>
    <script type="text/javascript" src="/static/js/bootstrap.js"></script>
</head>
<!--body onload="connect(path,myonmessage);"-->
<body>




    <div class="container">

    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" id="title" href="#">Project name</a>

          <ul class="nav pull-right">
              <li class="dropdown">
                    <a href="#" id="joinButton" class="dropdown-toggle" data-toggle="dropdown" data-target="#">Join<b class="caret"></b></a>
                    <ul class="dropdown-menu" role="menu">
                        <li>                        
                            <form id="joinform" action="javascript:join();">
                            <i class="icon-user"></i>Your name:<br/>
                            <input type="text" id="player"/>
                            </form>
                        </li>
                    </ul>
              </li>
          </ul>

        </div>
      </div>
    </div>




        <div class="page-header">
            <h1 id="title2"></h1>
        </div>
        <div class="row">
        <div class="span3">
            Connected:
            <ul id="mylist" class="nav nav-tabs nav-stacked">
            </ul>
            <form id="joinform" action="/login/uk" method="POST">
            Name:<input type="text" id="name" name="player"/><input type="submit" value="Join"/>
            </form>
        </div>
        <div class="span6">
            <div id="wrapper">
                <canvas id="my_canvas" width="500" height="500">
                    Fallback content here
                </canvas>
                <div id="buttonWrapper">
                    <input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="span6 offset4">
            <button type="button"  class="btn btn-danger" onclick="steer(-10)"><i class="icon-hand-left icon-white"></i>&nbsp;Left</button>
            <button type="button"  class="btn btn-success" onclick="steer(10)">Right&nbsp;<i class="icon-hand-right icon-white"></i></button>
        </div>        
    </div>
</div> 
<!--
    <div class="top">    
        <div class="left">
            <canvas id="my_canvas" width="500" height="500">
                Fallback content here
            </canvas>
        </div>
        <div class="right">
            <div class="page-header">
                <h1 id="title"></h1>
            </div>
            <div class="ctrl-group">
                Connected:
                <ul id="mylist" class="nav nav-tabs nav-stacked">
                </ul>
                <form action="javascript:join();">
                Name:<input type="text" id="name"/><input type="submit" value="Join"/>
                </form>
            </div>
        </div>
    </div>
    -->
    {{#NOTLOGGED}}Not connected{{/NOTLOGGED}}
    {{#LOGGED}}Connected as {{PLAYER}}{{/LOGGED}}
 </body>
<script type="text/javascript">
console.log("START"); 
var colors=[
"#00ffff", "#000000", "#0000ff", "#ff00ff",
"#008000", "#808080", "#00ff00", "#800000",
"#000080", "#808000", "#800080", "#ff0000",
"#c0c0c0", "#008080", "#ffffff", "#ffff00"];


var CANVAS_WIDTH=500;
var CANVAS_HEIGHT=500;
var AREA_WIDTH=2000;
var AREA_HEIGHT=2000;
var TILE_SIZE=50;

var MIN_SCALE=CANVAS_HEIGHT / AREA_HEIGHT;
var MAX_SCALE=2;
var scale = 1.0;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
var translatePos = {
    x: 0,
    y: 0
};

var cachedState={};
var boats=[];

var pathArray = window.location.pathname.split( '/' );
var race = pathArray[pathArray.length-1];

function addStatus(text){
	var date = new Date();
//	document.getElementById('status').innerHTML
//		= document.getElementById('status').innerHTML
//		+ date + ": " + text + "<br/>";
   // console.log( date + ":" + text);
}

function join(){
    var name = document.getElementById('name').value;
    ws.send("JOIN"+name);
    //document.getElementById('joinform').style.display = 'none';
}

function steer(angle){
    ws.send("STEER"+angle);
   // ws.send("MESG{john,\"Hello, John!\"}");
}

function updateList(state){
	var ul = document.getElementById('mylist');
    ul.innerHTML = "";
    for ( var i in state.fleet ){
        var newElement = document.createElement('li');
        var newLink = document.createElement('a');
        newLink.setAttribute('href','/race/'+state.fleet[i].name);

        newLink.innerHTML='<font color="'+colors[i]+'">'+state.fleet[i].name+'</font>';
        newElement.appendChild(newLink);
        ul.insertBefore(newElement,ul.firstChild);
    }
}


function getWeatherAt(i,j){
    var weatherCode = cachedState.weather.substring((i*AREA_HEIGHT/TILE_SIZE+j)*2,(i*AREA_HEIGHT/TILE_SIZE+j)*2+2);
    var force = parseInt(weatherCode.substring(0,1),16);
    var angle = 6.28 * parseInt(weatherCode.substring(1,2),16) / 16;
    return { "force": force , "angle": angle }; 
}




function drawTile(context,i,j){
    context.fillStyle = "#B0B0B0";
    context.fillRect(0,0,50,50);
    context.strokeStyle = "#909090";


    // Draw weather arrow
    context.save();
    context.translate(TILE_SIZE/2,TILE_SIZE/2);
    context.rotate( getWeatherAt(i,j).angle );
    //context.rotate(6.28 / 30 );
    context.beginPath();
    context.moveTo(-15,0);
    context.lineTo(15,0);
    context.lineTo(5,-5);
    context.moveTo(15,0);
    context.lineTo(5,5);
    context.stroke();
    context.restore();

    // Draw x,y text
    context.fillStyle = "black";
    context.font = "bold 10px sans-serif";
    context.textBaseline = "top";
    context.fillText(i+"x"+j, 0, 0);
    //context.fillText(getWeatherAt(i,j),0,-40);

}


function drawSea(context,x,y, width, height){
        context.lineWidth=1;

        //console.log("x="+x+", y="+y+", w="+width+", h="+height);
        if (x<0) x=0;
        if (y<0) y=0;
        if ( (x+width)>AREA_WIDTH ) x=AREA_WIDTH-width-1;
        if ( (y+height)>AREA_HEIGHT ) y=AREA_HEIGHT-height-1;

        //var leftmostTile=Math.max(0,Math.floor(-1*translatePos.x / TILE_SIZE));
        var leftmostTile = Math.floor(x / TILE_SIZE);


        //console.log("leftmost="+leftmostTile);
        var topmostTile =Math.floor( y / TILE_SIZE);

        //var rightmostTile=Math.min(leftmostTile + width / TILE_SIZE, AREA_WIDTH / TILE_SIZE);
        var rightmostTile = Math.floor( (x+width)/TILE_SIZE);

        //console.log("rightmost="+rightmostTile);
        var bottommostTile=Math.floor( (y + height) / TILE_SIZE);

        for ( var i=leftmostTile; i <= rightmostTile ; i++ ){
            for ( var j=topmostTile ; j <= bottommostTile ; j++ ){
                context.save();
                context.translate(i*TILE_SIZE,j*TILE_SIZE);
                drawTile(context,i,j);
                context.restore();
            }
        }
}

function draw(){
    var canvas = document.getElementById('my_canvas');
    if (canvas.getContext){
        var context = canvas.getContext('2d');
        //context.clearRect(0, 0, canvas.width, canvas.height);
        context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
        context.strokeStyle = "#000000";

        context.save();
        context.translate(translatePos.x, translatePos.y);
        context.scale(scale, scale);

        //console.log("Sea drawing: x="+(-translatePos.x/scale)+", y="+(translatePos.y/scale)+", w="+(CANVAS_WIDTH/scale)+", scale="+scale);
        drawSea(context, -translatePos.x/scale, -translatePos.y/scale, CANVAS_WIDTH/scale, CANVAS_HEIGHT/scale);
        for ( var i in boats ){
            context.fillStyle = colors[i];
            context.beginPath();
            context.arc(boats[i].xpos,boats[i].ypos,10,0,Math.PI*2,true);
            context.closePath();
            context.stroke();
            context.fill();
        }

        context.restore();
        context.strokeStyle="#ff0000";
        context.beginPath();
        context.moveTo(50,0);
        context.lineTo(50,500);
        context.stroke();
    }
}


function verifyAndSetOffset(x,y){
    if ( x > 0 ) x=0;
    if ( y > 0 ) y=0;

    if ( -x  < (AREA_WIDTH*scale-CANVAS_WIDTH) ){
        translatePos.x = x;
    } else {
       translatePos.x = -(AREA_WIDTH*scale-CANVAS_WIDTH)+1;
    }

    if ( -y < (AREA_HEIGHT*scale - CANVAS_HEIGHT ) ) {
       translatePos.y = y;
    } else {
       translatePos.y = -(AREA_HEIGHT*scale-CANVAS_HEIGHT)+1;
    }
}

function myonmessage(evt) {
    var receivedMsg = evt.data; 
    console.log(evt.data);
    if (evt.data instanceof Blob) {
        console.log(evt.data.parts);
    } else {
        if (evt.data.charAt(0)=='{') {
            var state = eval("("+evt.data+")");
            if (state.weather != undefined ){cachedState = state}
            boats = state.fleet;
                    draw();    
                    updateList(eval("("+evt.data+")"));
                }
            addStatus(evt.data);
    }
}

document.getElementById("plus").addEventListener("click", function(){
        if ( scale/scaleMultiplier < MAX_SCALE ){
            scale /= scaleMultiplier;
            draw();
        }
                }, false);
                
document.getElementById("minus").addEventListener("click", function(){
        if (scale*scaleMultiplier>MIN_SCALE){
        scale *= scaleMultiplier;
        verifyAndSetOffset(translatePos.x, translatePos.y);
        draw();
        }
                }, false);

document.getElementById('my_canvas').addEventListener("mousedown", function(evt){
                    mouseDown = true;
                    startDragOffset.x = evt.clientX - translatePos.x;
                    startDragOffset.y = evt.clientY - translatePos.y;
                });

document.getElementById('my_canvas').addEventListener("mouseup", function(evt){
    mouseDown = false;
});

document.getElementById('my_canvas').addEventListener("mouseover", function(evt){
    mouseDown = false;
});

document.getElementById('my_canvas').addEventListener("mouseout", function(evt){
    mouseDown = false;
});

document.getElementById('my_canvas').addEventListener("mousemove", function(evt){
        if ( mouseDown ){
            //console.log("oldx="+translatePos.x+", oldy="+translatePos.y+", scale="+scale);
            var newtranslatePosX = evt.clientX - startDragOffset.x;
            var newtranslatePosY = evt.clientY - startDragOffset.y;
            ////console.log("DRAG: x="+newtranslatePosX+" ,y="+newtranslatePosY+", scale="+scale);
            //if ( newtranslatePosX > 0 ) {
            //        newtranslatePosX=0;
           // }

           // if ( newtranslatePosY > 0 ) {
           //     newtranslatePosY=0;
           // }

            ////if (  newtranslatePosX < 0 &&  (( AREA_WIDTH - CANVAS_WIDTH ) > Math.abs( newtranslatePosX))){
            //console.log("LIMIT="+(AREA_WIDTH-CANVAS_WIDTH)*scale);
            //if (  -newtranslatePosX  < (AREA_WIDTH*scale-CANVAS_WIDTH) ){
            //    translatePos.x = newtranslatePosX;
            //    } else {
            //        translatePos.x = -(AREA_WIDTH*scale-CANVAS_WIDTH)+1;
            //    }

            //if ( -newtranslatePosY < (AREA_HEIGHT*scale - CANVAS_HEIGHT ) ) {
            //    translatePos.y = newtranslatePosY;
            //} else {
            //    translatePos.y = -(AREA_HEIGHT*scale-CANVAS_HEIGHT)+1;
            //}

            //console.log("newx="+translatePos.x+", newy="+translatePos.y+", scale="+scale);
            verifyAndSetOffset(newtranslatePosX, newtranslatePosY);
            draw();
      }
});

connect('race/'+race,myonmessage,function(){ws.send('HELLO')});
document.getElementById('title').innerHTML = race;
$('.dropdown-toggle').dropdown();
</script>
</html>

